import React, { createContext, useContext, useState, useCallback } from 'react';

// 创建 Context
const ChatContext = createContext();

// Provider 组件
export const ChatProvider = ({ children }) => {
    // 状态定义
    const [generalChatMessages, setGeneralChatMessages] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);

    // 更新聊天消息
    const updateGeneralChatMessages = useCallback((messages) => {
        setGeneralChatMessages(messages);
    }, []);

    // 添加新消息
    const addMessage = useCallback((message) => {
        setGeneralChatMessages(prev => [...prev, message]);
    }, []);

    // 清空消息
    const clearMessages = useCallback(() => {
        setGeneralChatMessages([]);
    }, []);

    // 设置加载状态
    const setLoading = useCallback((loading) => {
        setIsLoading(loading);
    }, []);

    // 设置错误信息
    const setErrorMessage = useCallback((error) => {
        setError(error);
    }, []);

    // Context 值
    const value = {
        generalChatMessages,
        updateGeneralChatMessages,
        addMessage,
        clearMessages,
        isLoading,
        setLoading,
        error,
        setErrorMessage
    };

    return (
        <ChatContext.Provider value={value}>
            {children}
        </ChatContext.Provider>
    );
};

// 自定义 Hook
export const useChat = () => {
    const context = useContext(ChatContext);
    if (!context) {
        throw new Error('useChat must be used within a ChatProvider');
    }
    return context;
}; 